// 重新设计的API服务 - 每个功能独立的JSON文件
// URL格式：/mock/api/模块/功能.json

// 基础请求函数
const request = async (url: string) => {
  try {
    const response = await fetch(url)
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    return data
  } catch (error) {
    console.error('API请求失败:', error)
    throw error
  }
}

// ===== 用户相关API =====
export const userApi = {
  // 获取用户列表
  getUsers: () => request('/mock/api/users/list.json'),
  
  // 获取用户详情（从列表中查找）
  getUserById: async (id: string) => {
    const users = await request('/mock/api/users/list.json')
    const user = users.find((u: any) => u.id === id)
    if (!user) {
      throw new Error('用户不存在')
    }
    return user
  },
}

// ===== 商品相关API =====
export const productApi = {
  // 获取所有商品列表
  getProducts: () => request('/mock/api/products/list.json'),
  
  // 获取热门商品
  getHotProducts: () => request('/mock/api/products/hot.json'),
  
  // 获取商品详情（从热门商品中查找）
  getProductById: async (id: string) => {
    const products = await request('/mock/api/products/hot.json')
    const product = products.find((p: any) => p.id === id)
    if (!product) {
      // 如果热门商品中没有，再从全部商品中查找
      const allProducts = await request('/mock/api/products/list.json')
      const foundProduct = allProducts.find((p: any) => p.id === id)
      if (!foundProduct) {
        throw new Error('商品不存在')
      }
      return foundProduct
    }
    return product
  },
  
  // 根据分类ID获取商品
  getProductsByCategory: async (categoryId: string) => {
    const products = await request('/mock/api/products/list.json')
    const filteredProducts = products.filter((product: any) => 
      product.categoryId === categoryId
    )
    return filteredProducts
  },
  
  // 搜索商品（简单的客户端搜索）
  searchProducts: async (keyword: string) => {
    const products = await request('/mock/api/products/list.json')
    const filteredProducts = products.filter((product: any) => 
      product.name.includes(keyword) || product.description.includes(keyword)
    )
    return {
      list: filteredProducts,
      total: filteredProducts.length
    }
  },
  
  // 获取商品分类
  getCategories: () => request('/mock/api/categories/list.json'),
}

// ===== 订单相关API =====
export const orderApi = {
  // 获取订单列表
  getOrders: () => request('/mock/api/orders/list.json'),
  
  // 获取订单详情
  getOrderById: async (id: string) => {
    const orders = await request('/mock/api/orders/list.json')
    const order = orders.find((o: any) => o.id === id)
    if (!order) {
      throw new Error('订单不存在')
    }
    return order
  },
  
  // 根据用户ID获取订单
  getOrdersByUserId: async (userId: string) => {
    const orders = await request('/mock/api/orders/list.json')
    const userOrders = orders.filter((order: any) => order.userId === userId)
    return userOrders
  },
  
  // 创建订单（模拟）
  createOrder: async (orderData: any) => {
    console.log('创建订单:', orderData)
    // 模拟创建成功
    return {
      id: Date.now().toString(),
      orderNo: 'ORD' + Date.now(),
      ...orderData,
      status: 'pending',
      createdAt: new Date().toISOString()
    }
  },
}

// ===== 认证相关API =====
export const authApi = {
  // 用户登录
  login: async (credentials: { username: string; password: string }) => {
    console.log('用户登录:', credentials)
    
    // 简单的模拟验证
    if (credentials.username === 'test' && credentials.password === '123456') {
      return await request('/mock/api/auth/login.json')
    } else {
      throw new Error('用户名或密码错误')
    }
  },
  
  // 用户注册（模拟）
  register: async (userData: any) => {
    console.log('用户注册:', userData)
    // 模拟注册成功
    return {
      success: true,
      message: '注册成功',
      data: {
        id: Date.now().toString(),
        ...userData,
        createdAt: new Date().toISOString()
      }
    }
  },
  
  // 获取用户信息（模拟）
  getUserInfo: async () => {
    const loginData = await request('/mock/api/auth/login.json')
    return loginData.data.user
  },
}

// 导出默认API对象
export default {
  user: userApi,
  product: productApi,
  order: orderApi,
  auth: authApi,
} 